package com.nulldev.util.web.YouTubeExtractor.subtitles.types;

import java.util.List;
import java.util.regex.Pattern;

import com.nulldev.util.JVM.Arguments;
import com.nulldev.util.VariableAPI.ArrayUtils;
import com.nulldev.util.VariableAPI.StringsUtil;
import com.nulldev.util.VariableAPI.util.strings.splitters.Splitters;
import com.nulldev.util.data.Arrays.arrays.FastLists;
import com.nulldev.util.data.legacy.XML.lXML;
import com.nulldev.util.data.legacy.XML.lXML.Doc;
import com.nulldev.util.data.legacy.XML.lXML.E;
import com.nulldev.util.logging.Logger;
import com.nulldev.util.logging.LoggerFactory;
import com.nulldev.util.web.YouTubeExtractor.subtitles.Subtitle;
import com.nulldev.util.web.YouTubeExtractor.subtitles.SubtitleParser;

public class TTMLSubtitleParser {
	private static final Logger log = LoggerFactory.getLoggerD(Arguments.hasArgument("--Subtitles.debug"));

	public static List<Subtitle> getSubtitles(final String data) {
		if (data == null)
			throw new NullPointerException("getSubtitles() -> data == null!");
		final List<Subtitle> out = FastLists.list(32);
		if (SubtitleParser.USE_NEW_LOGIC) {
			final Doc o = lXML.doc(data);
			final E transcript = o.root();
			for (final E _entry : transcript.children("text")) {
				final String entry = _entry.toString();
				try {
					final String text = ArrayUtils.StringArrayUtils.addFrom(Splitters.splitString(entry, "\">"), 1);
					final float start = Float.parseFloat(_entry.getAttr("start").value());
					String _dur = "1.000";
					try {
						_dur = _entry.getAttr("dur").value();
					} catch (Exception e) {
					}
					final float dur = Float.parseFloat(_dur);
					out.add(new Subtitle(text, start, dur));
				} catch (Exception e) {
					log.error("Failed to process subtitle entry. [e=" + entry + "]", e);
				}
			}
		} else {
			final String innerData = StringsUtil.substringBetweenO(data, "<?xml version=\"1.0\" encoding=\"utf-8\" ?><transcript>", "</transcript>");
			final String[] entries = innerData.split(Pattern.quote("</text>"));
			for (final String entry : entries) {
				try {
					final String text = ArrayUtils.StringArrayUtils.addFrom(Splitters.splitString(entry, "\">"), 1);
					final float start = Float.parseFloat(StringsUtil.substringBetweenO(entry, "start=\"", "\""));
					final String _dur = StringsUtil.substringBetweenO(entry, "dur=\"", "\"");
					final float dur = Float.parseFloat(_dur);
					out.add(new Subtitle(text, start, dur));
				} catch (Exception e) {
					log.error("Failed to process subtitle entry. [e=" + entry + "]", e);
				}
			}
		}
		return out;
	}
}
